package patientimport;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.ErrorCode;

public class LehuiToFollow2 {
 	/*public static final String POST_URL_CALL = "http://doctor.bb-care.com:9090/followup/service/patient/patientAdd?sessionId=26bf589d-3274-4e4f-9f1c-22cf6c571506";
    public static final String POST_QUES_CALL = "http://doctor.bb-care.com:9090/followup/service/patient/patientTaskContentDataModify?sessionId=26bf589d-3274-4e4f-9f1c-22cf6c571506";
    public static final String dbUrl = "jdbc:mysql://rdsap8226j2iuruyoaamgpublic.mysql.rds.aliyuncs.com/bbcare_cloud";
    public static final String dbUrlOms = "jdbc:mysql://rdsap8226j2iuruyoaamgpublic.mysql.rds.aliyuncs.com/bbcare_oms";
    public static final String dbUser = "******";
    public static final String dbPwd = "******";*/

	public static final String POST_URL_CALL = "http://doctor.bb-care.com:9090/followup/service/patient/patientAdd?sessionId=0b389849-8015-4f5e-a0e9-0d00d06d3403";
    public static final String POST_QUES_CALL = "http://192.168.1.102:18080/followup/service/patient/patientTaskContentDataModify?sessionId=9c1101b9-11ce-4dc0-95f8-542050b9eb2d";
    //public static final String dbUrl = "jdbc:mysql://rdsap8226j2iuruyoaamgpublic.mysql.rds.aliyuncs.com/test_temp_user";
    public static final String dbUrl = "jdbc:mysql://rdsap8226j2iuruyoaamgpublic.mysql.rds.aliyuncs.com/bbcare_cloud";
    //public static final String dbUrlOms = "jdbc:mysql://rdsap8226j2iuruyoaamgpublic.mysql.rds.aliyuncs.com/test_test";
    public static final String dbUrlOms = "jdbc:mysql://rdsap8226j2iuruyoaamgpublic.mysql.rds.aliyuncs.com/bbcare_oms";
    //public static final String dbUser = "zh_xiong";
    //public static final String dbPwd = "xzh123456";
    public static final String dbUser = "yunyin";
    public static final String dbPwd = "cl123456";
    
    //随访2.0生长发育接口
    public static final String POST_URL_GROETH = "http://192.168.1.105:8686/followup/webapi/service/wechat/growth/addgrowth";
    //智力发育和养育环境评估接口
    public static final String POST_URL_GETSCORE = "http://192.168.1.105:8686/followup/webapi/service/evaluation/getScore";

    public static JSONObject httpPostCall(String parm2, String callUrl) throws Exception {
        try {
            URL url = new URL(callUrl);
            System.out.println("url==" + callUrl);

            // 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接
            // (标识一个url所引用的远程对象连接)
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中

            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
            connection.setDoOutput(true);

            // 设置连接输入流为true
            connection.setDoInput(true);

            // 设置请求方式为post
            connection.setRequestMethod("POST");

            // post请求缓存设为false
            connection.setUseCaches(true);

            // 设置该HttpURLConnection实例是否自动执行重定向
            connection.setInstanceFollowRedirects(true);

            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
            // application/x-javascript text/xml->xml数据
            // application/x-javascript->json对象
            // application/x-www-form-urlencoded->表单数据
            // ;charset=utf-8 必须要，不然会出现乱码
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("contentType", "UTF-8");
            // connection.setRequestProperty("Cookie", cookie);

            // 建立连接
            // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            connection.connect();

            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
            OutputStreamWriter dataout = new OutputStreamWriter(connection.getOutputStream());
            System.out.println("parm2==[" + parm2 + "]");
           // net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(parm2);

            // 将参数输出到连接
            // dataout.writeBytes(parm2);
            dataout.write(parm2);

            // 输出完成后刷新并关闭流
            dataout.flush();
            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)

            // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder(); // 用来存储响应数据

            // 循环读取流,若不到结尾处
            while ((line = bf.readLine()) != null) {
                // sb.append(bf.readLine());
                sb.append(line).append(System.getProperty("line.separator"));
            }
            // ---{"success":true,"data":{"patientId":"14o4ajITLRMI5Zxc4ynK","ptSchemeId":"15pQ0sXjE67NEXSCxBIi"}}
            System.out.println("---" + sb.toString());
            bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
            connection.disconnect(); // 销毁连接

            JSONObject jsonArg = null;
            try {
                jsonArg = JSON.parseObject(sb.toString());
            } catch (Exception ex) {
                // ex.printStackTrace();
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "出参格式错误，非json格式！"));
            }
            boolean retFlag = jsonArg.getBooleanValue("success");
            if (!retFlag) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR,
                        "调用失败：" + jsonArg.getString("msg")));
            }
            if (POST_URL_CALL.equals(callUrl)) {
                JSONObject jsonData = jsonArg.getJSONObject("data");
                if (null == jsonData) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR,
                            "调用失败：返回无data节点!"));
                }
            }

            return jsonArg;
        } catch (Exception e) {
            e.printStackTrace();
            throw (e);
        }
	}

    public static void migrateData() {
        int irow = 0;
        int succNum = 0;
        int errNum = 0;
        // 声明Connection对象
        Connection con = null;
        Connection connOms = null;
        // 驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名mydata
        String url = dbUrl;
        // MySQL配置时的用户名
        String user = dbUser;
        // MySQL配置时的密码
        String password = dbPwd;
        //队列和code和dept_id相关联
        Map<String,Object> mapQueue = new HashMap<String,Object>();
        mapQueue.put("12LEHUI000000001", "14");
        mapQueue.put("12LEHUI000000002", "01");
        mapQueue.put("12LEHUI000000003", "02");
        mapQueue.put("12LEHUI000000004", "03");
        mapQueue.put("12LEHUI000000005", "04");
        mapQueue.put("12LEHUI000000006", "05");
        mapQueue.put("12LEHUI000000007", "06");
        mapQueue.put("12LEHUI000000008", "07");
        mapQueue.put("12LEHUI000000009", "08");
        mapQueue.put("12LEHUI000000010", "09");
        mapQueue.put("12LEHUI000000011", "10");
        mapQueue.put("12LEHUI000000012", "11");
        mapQueue.put("12LEHUI000000013", "12");
        mapQueue.put("12LEHUI000000014", "13");
        mapQueue.put("12LEHUI000000015", "21");
        mapQueue.put("12LEHUI000000016", "15");
        mapQueue.put("12LEHUI000000017", "16");
        mapQueue.put("12LEHUI000000018", "17");
        mapQueue.put("12LEHUI000000019", "18");
        mapQueue.put("12LEHUI000000020", "19");
        mapQueue.put("12LEHUI000000021", "20");
        mapQueue.put("12LEHUI000000022", "23");
        mapQueue.put("12LEHUI000000023", "297ebe0e55ec6adf0155f3d0939551e8");
        mapQueue.put("12LEHUI000000024", "24");
        mapQueue.put("12LEHUI000000025", "25");
        mapQueue.put("12LEHUI000000026", "26");
        mapQueue.put("12LEHUI000000027", "27");
        mapQueue.put("12LEHUI000000028", "28");
        mapQueue.put("12LEHUI000000029", "29");
        mapQueue.put("12LEHUI000000030", "30");
        mapQueue.put("12LEHUI000000031", "31");
        mapQueue.put("12LEHUI000000032", "32");
        mapQueue.put("12LEHUI000000033", "33");
        mapQueue.put("12LEHUI000000034", "34");
        
        long time = System.currentTimeMillis();
        
        try {
            // 加载驱动程序
            Class.forName(driver);
            // 1.getConnection()方法，连接MySQL数据库
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                System.out.println("------Succeeded connecting to the Database!");
            }
            con.setAutoCommit(false);

            connOms = DriverManager.getConnection(dbUrlOms, user, password);
            if (!connOms.isClosed()) {
                System.out.println("------Succeeded connecting to the oms Database!");
            }
            connOms.setAutoCommit(false);
        } catch (SQLException e) {
            // 数据库连接失败异常处理
            e.printStackTrace();
            return;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }

        long time2 = System.currentTimeMillis();
        System.out.println("currentTimeMillis22222："+(time2-time));
        // 遍历查询结果集
        try {

            // 创建statement类对象，用来执行SQL语句！！
            Statement statement = connOms.createStatement();
            Statement stmtOms = connOms.createStatement();
            Statement stmtOms1 = connOms.createStatement();
            //1. 查询需要移植的患者	
          /*  String sql ="select a.id,a.user_name,a.phone_no,b.queue_id from pt_user_info a, pt_queuescheme_info b \r\n" + 
            		"where a.id = b.user_id \r\n" + 
            		"and b.user_status='1' \r\n" + 
            		"and a.user_type='1' \r\n" + 
            		"and a.tenant_id=b.tenant_id \r\n" + 
            		"and a.tenant_id='LEHUI001'";*/
            String sql = "select * from pt_user_info_lehui_02 where deal_status='2' and queue_id='12LEHUI000000001'";
            System.out.println("----------sql==" + sql);
            // 2.ResultSet类，用来存放获取的结果集
            ResultSet rs = statement.executeQuery(sql);
            //如果查询不到数据立即结束
            if(rs==null) {
            	return;
            }
            //换成list
            List<Map<String,Object>> list = resultSetToList(rs);
            
            int count = 1000;// 一个线程处理2000条数据
    		int listSize = list.size();// 数据集合大小
    		int runSize = (listSize / count) + 1; // 开启的线程数
    		List<Map<String, Object>> newlist = null;// 存放每个线程的执行数据
    		ExecutorService executor = Executors.newFixedThreadPool(runSize);// 创建一个线程池，数量和开启线程的数量一样
    		// 创建两个个计数器
    		CountDownLatch begin = new CountDownLatch(1);
    		CountDownLatch end = new CountDownLatch(runSize);
    		// 循环创建线程
    		for (int i = 0; i < runSize; i++) {
    			String str = "第"+i+"线程";
    			// 计算每个线程执行的数据
    			if ((i + 1) == runSize) {
    				int startIndex = (i * count);
    				int endIndex = list.size();
    				newlist = list.subList(startIndex, endIndex);
    			} else {
    				int startIndex = (i * count);
    				int endIndex = (i + 1) * count;
    				newlist = list.subList(startIndex, endIndex);
    			}
    			// 线程类
    			MyThread mythead = new MyThread(newlist, begin, end,mapQueue,con,str,connOms );
    			// 这里执行线程的方式是调用线程池里的executor.execute(mythead)方法。
    			executor.execute(mythead);
    		}

    		begin.countDown();
    		end.await();

    		// 执行完关闭线程池
    		executor.shutdown();
            
            rs.close();
            statement.close();
            stmtOms.close();
            con.close();
            connOms.close();
            stmtOms1.close();
        } catch (SQLException e) {
            // 数据库连接失败异常处理
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } finally {
            System.out.println("----------total: " + irow);
            System.out.println("----------success: " + succNum);
            System.out.println("----------error: " + errNum);
        }
    }

    /**
     * 查询用户生长发育信息，并调用随访2.0接口保存数据
     * @param rs4  评估记录
     * @param stm 创建的数据库链接
     * @param deptId 科室id
     * @param userId 用户id
     * @param queueId 队列id
     * @throws SQLException 
     * @throws ParseException 
     * 
     **/
    public static boolean saveGrowth(ResultSet rs4, Statement stm,Statement stm1,String deptId,String userId,String queueId,Connection con) throws SQLException, ParseException {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    	//答题记录id
    	String _babyQuestionRecord_id = "";
    	//更新时间
    	String updateTime = null;
    	//问题题目
    	String  _quastionName = "";
    	//体重
    	String weight="";
    	//身高
    	String height="";
    	//创建链接
    	Statement stmt6 = con.createStatement(); 
    	Map<String,Object> map = new HashMap<String,Object>();
    	Map<String,Object> mapIn = new HashMap<String,Object>();
    	//评估记录可能有多条
    	while(rs4.next()){
    		map.clear();
    		mapIn.clear();
    		//渠道类型
    		map.put("channel", "BBCARE-APP");
    		//渠道来源
    		map.put("sourceType", "4");
    		//科室id
    		map.put("deptId", deptId);
    		//用户id
    		map.put("userId", userId);
    		//队列id
    		map.put("queueId", queueId);
    		_babyQuestionRecord_id = rs4.getString("_id");
    		//备注
    		map.put("remark", "乐惠数据移植："+_babyQuestionRecord_id);
    		updateTime = rs4.getString("_updateTime");
    		map.put("createTime", sdf.format(sdf.parse(updateTime)));
    		map.put("testTime", sdf1.format(sdf1.parse(updateTime)));
    		String sqldetail = "select * from t_babyquestiondetail where _babyQuestionRecord_id='"+_babyQuestionRecord_id+"' order by _createTime ";
    		//查询答题详情
    		ResultSet rs5 = stm1.executeQuery(sqldetail);
    		if(rs5==null) {
    			continue;
    		}
    		boolean flag1 = false;
    		boolean flag2 = false;
    		while(rs5.next()) {
    			_quastionName = rs5.getString("_question_name");
    			if(_quastionName.indexOf("cm") !=-1) {
    				//判断是身高
    				height = rs5.getString("_note");
    				map.put("height", height);
    				flag1 =  true;
    			}else if(_quastionName.indexOf("kg") !=-1) {
    				//判断是体重
    				weight = rs5.getString("_note");
					map.put("weight", weight);
					flag2 = true;
    			}
    			if(flag1==true&&flag2==true) {
    				break;
    			}
    		}
    		//获取到身高体重之后调用随访2.0接口将身高体重入表
    		//1.拼接调用接口入参
    		mapIn.put("data", map);
    		//将map转成json字符串
    		String json = JSONObject.toJSONString(mapIn);
    		//调用随访2.0接口
    		try {
				JSONObject jsons  = httpPostCall(json,POST_URL_GROETH);
				if(jsons.getBooleanValue("success")) {
					String updateSql = "update t_babyquestionrecord_20180419 set deal_status='1' where _id='" + _babyQuestionRecord_id + "'";
	   			    stmt6.executeUpdate(updateSql);
	   			 	con.commit();
				}else {
					String updateSql = "update t_babyquestionrecord_20180419 set deal_status='0' where _id='" + _babyQuestionRecord_id + "'";
	   			    stmt6.executeUpdate(updateSql);
	   			 	con.commit();
				}
			} catch (Exception e) {
				String updateSql = "update t_babyquestionrecord_20180419 set deal_status='0' where _id='" + _babyQuestionRecord_id + "'";
   			    stmt6.executeUpdate(updateSql);
   			 	con.commit();
				System.out.println(e);
			}
    	}
    	stmt6.close();
		return false;
    }
    
    
    /**
     * 查询智能发育评估信息，并调用随访2.0接口保存数据
     * @param rs4  评估记录
     * @param stm 创建的数据库链接
     * @param deptId 科室id
     * @param userId 用户id
     * @param queueId 队列id
     * @throws SQLException 
     * @throws NumberFormatException 
     * @throws ParseException 
     * 
     **/
    public static boolean saveZnfy(ResultSet rs4, Statement stm,Statement stm1,String deptId,String userId,String queueId,Connection con) throws NumberFormatException, SQLException, ParseException {
    	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	//答题记录id
    	String _babyQuestionRecord_id = "";
    	//更新时间
    	String updateTime = null;
    	Map<String,Object> map = new HashMap<String,Object>();
    	Map<String,Object> mapIn = new HashMap<String,Object>();
    	//创建链接
    	Statement stmt6 = con.createStatement(); 
    	//评估记录可能有多条
    	while(rs4.next()){
    		Map<String,Object> map1 = new HashMap<String,Object>();
    		int i = 1;
    		map.clear();
    		mapIn.clear();
    		//渠道类型
    		map.put("channel", "BBCARE-APP");
    		//渠道来源
    		map.put("sourceType", "4");
    		//评估类型
    		map.put("evaluationType", "ASQ");
    		//科室id
    		map.put("deptId", deptId);
    		//用户id
    		map.put("userId", userId);
    		//队列id
    		map.put("queueId", queueId);
    		_babyQuestionRecord_id = rs4.getString("_id");
    		//备注
    		map.put("remark", "乐惠数据移植智能："+_babyQuestionRecord_id);
    		updateTime = rs4.getString("_updateTime");
    		System.out.println(updateTime);
    		map.put("createTime", sdf.format(sdf.parse(updateTime)));
    		map.put("testTime", sdf1.format(sdf1.parse(updateTime)));
    		String sqldetail = "select b._note from  t_babyquestiondetail a, t_options b  where a._optionId=b._id  and a._babyQuestionRecord_id= '"+_babyQuestionRecord_id+"' ORDER BY a._createTime";
    		//查询答题详情
    		ResultSet rs5 = stm1.executeQuery(sqldetail);
    		if(rs5==null) {
    			continue;
    		}
    		while(rs5.next()) {
    			map1.put(i+"", replace(rs5.getString("_note"),"ASQ"));
    			i++;
    		}
    		//获取到智力发育得分之后调用随访2.0接口入表
    		//1.拼接调用接口入参
    		map.put("postionIds", JSONObject.toJSONString(map1));
    		mapIn.put("data", map);
    		//将map转成json字符串
    		String json = JSONObject.toJSONString(mapIn);
    		//调用随访2.0接口
    		try {
				JSONObject jsons  = httpPostCall(json,POST_URL_GETSCORE);
				if(jsons.getBooleanValue("success")) {
					String updateSql = "update t_babyquestionrecord_20180419 set deal_status='1' where _id='" + _babyQuestionRecord_id + "'";
	   			    stmt6.executeUpdate(updateSql);
	   			 	con.commit();
				}else {
					String updateSql = "update t_babyquestionrecord_20180419 set deal_status='0' where _id='" + _babyQuestionRecord_id + "'";
	   			    stmt6.executeUpdate(updateSql);
	   			 	con.commit();
				}
			} catch (Exception e) {
				String updateSql = "update t_babyquestionrecord_20180419 set deal_status='0' where _id='" + _babyQuestionRecord_id + "'";
   			    stmt6.executeUpdate(updateSql);
   			 	con.commit();
				System.out.println(e);
			}
    	}
    	stmt6.close();
		return false;
    }
    
    
    /**
     * 查询用户养育环境测量信息，并调用随访2.0接口保存数据
     * @param rs4  评估记录
     * @param stm 创建的数据库链接
     * @param deptId 科室id
     * @param userId 用户id
     * @param queueId 队列id 
     * @throws SQLException 
     * @throws NumberFormatException 
     * @throws ParseException 
     * 
     **/
    public static boolean saveYyhj(ResultSet rs4, Statement stm,Statement stm1,String deptId,String userId,String queueId,Connection con) throws NumberFormatException, SQLException, ParseException {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    	//答题记录id
    	String _babyQuestionRecord_id = "";
    	//更新时间
    	String updateTime = null;
    	Map<String,Object> map = new HashMap<String,Object>();
    	Map<String,Object> mapIn = new HashMap<String,Object>();
    	//创建链接
    	Statement stmt6 = con.createStatement(); 
    	//评估记录可能有多条
    	while(rs4.next()){
    		Map<String,Object> map1 = new HashMap<String,Object>();
    		int i = 1;
    		map.clear();
    		mapIn.clear();
    		//渠道类型
    		map.put("channel", "BBCARE-APP");
    		//渠道来源
    		map.put("sourceType", "4");
    		//评估类型
    		map.put("evaluationType", "AHEMD-IS");
    		//科室id
    		map.put("deptId", deptId);
    		//用户id
    		map.put("userId", userId);
    		//队列id
    		map.put("queueId", queueId);
    		_babyQuestionRecord_id = rs4.getString("_id");
    		//备注
    		map.put("remark", "乐惠数据移植养育："+_babyQuestionRecord_id);
    		updateTime = rs4.getString("_updateTime");
    		map.put("createTime", sdf.format(sdf.parse(updateTime)));
    		map.put("testTime", sdf1.format(sdf1.parse(updateTime)));
    		String sqldetail = "select b._note from  t_babyquestiondetail a, t_options b  where a._optionId=b._id  and a._babyQuestionRecord_id= '"+_babyQuestionRecord_id+"' ORDER BY a._createTime";
    		//查询答题详情
    		ResultSet rs5 = stm1.executeQuery(sqldetail);
    		if(rs5==null) {
    			continue;
    		}
    		while(rs5.next()) {
    			map1.put(i+"", replace(rs5.getString("_note"),"AHEMD-IS"));
    			i++;
    		}
    		//获取到养育环境得分之后调用随访2.0接口入表
    		//1.拼接调用接口入参
    		map.put("postionIds", JSONObject.toJSONString(map1));
    		mapIn.put("data", map);
    		//将map转成json字符串
    		String json = JSONObject.toJSONString(mapIn);
    		//调用随访2.0接口
    		try {
				JSONObject jsons  = httpPostCall(json,POST_URL_GETSCORE);
				if(jsons.getBooleanValue("success")) {
					String updateSql = "update t_babyquestionrecord_20180419 set deal_status='1' where _id='" + _babyQuestionRecord_id + "'";
	   			    stmt6.executeUpdate(updateSql);
	   			 	con.commit();
				}else {
					String updateSql = "update t_babyquestionrecord_20180419 set deal_status='0' where _id='" + _babyQuestionRecord_id + "'";
	   			    stmt6.executeUpdate(updateSql);
	   			 	con.commit();
				}
			} catch (Exception e) {
				String updateSql = "update t_babyquestionrecord_20180419 set deal_status='0' where _id='" + _babyQuestionRecord_id + "'";
   			    stmt6.executeUpdate(updateSql);
   			 	con.commit();
				System.out.println(e);
			}
    	}
    	stmt6.close();
		return false;
    }
    
    
    /**  
     * 判断字符串是否为数字  
     *   
     * @param str  
     * @return  
     */  
    public static boolean isNumeric(String str) {  
        Pattern pattern = Pattern.compile("[0-9]+([.]{1}[0-9]+){0,1}");  
        Matcher isNum = pattern.matcher(str);  
        if (!isNum.matches()) {  
            return false;  
        }  
        return true;  
    } 
    
    /**  
     * 将答案换算成分数
     *   
     * @param str  
     * @return  
     */  
    public static String replace(String str,String type) {
    	String score = "";
    	if(!StringUtils.isBlank(str)) {
	    	if("AHEMD-IS".equals(type)) {
	    		if("没有".equals(str)) {
	    			score = "1";
	        	}else if("有".equals(str)) {
	        		score = "2";
	        	}else if("否".equals(str) || "不是".equals(str)) {
	        		score = "1";
	        	}else if("是".equals(str)) {
	        		score = "2";
	        	}else if("从不".equals(str)) {
	        		score = "1";
	        	}else if("有时".equals(str)) {
	        		score = "2";
	        	}else if("经常".equals(str)) {
	        		score = "3";
	        	}else if("总是".equals(str)) {
	        		score = "4";
	        	}else if("0".equals(str)||"1".equals(str)) {
	        		score = "1";
	        	}else if("1-2".equals(str)) {
	        		score = "2";
	        	}else if("3个及以上".equals(str)) {
	        		score = "3";
	        	}
	    	}else {
	    		if("是".equals(str)) {
	    			score = "1";
	        	}else if("有时是".equals(str)) {
	        		score = "2";
	        	}else if("否".equals(str) || "不是".equals(str)) {
	        		score = "3";
	        	}
	    	}
    	}
    	
        return score;  
    } 
	    
    
    //将ResultSet转成list
    public static List<Map<String,Object>> resultSetToList(ResultSet rs) throws java.sql.SQLException {   
        ResultSetMetaData md = rs.getMetaData(); //得到结果集(rs)的结构信息，比如字段数、字段名等   
        int columnCount = md.getColumnCount(); //返回此 ResultSet 对象中的列数   
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();   
        Map<String,Object> rowData = new HashMap<String,Object>();   
        while (rs.next()) {   
         rowData = new HashMap<String,Object>(columnCount);   
         for (int i = 1; i <= columnCount; i++) {   
                 rowData.put(md.getColumnName(i), rs.getObject(i));   
         }   
         list.add(rowData);   
        }   
        return list;   
}
    
    
    public static void main(String[] args) {
        try {
        	long time = System.currentTimeMillis();
            migrateData();
            long time2 = System.currentTimeMillis();
            System.out.println("currentTimeMillis："+(time2-time));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
    //线程
 	private static class MyThread implements Runnable {
 		private List<Map<String,Object>> list;
 		private CountDownLatch begin;
 		private CountDownLatch end;
 		private Map<String,Object> mapQueue;
 		private Connection con;
 		private String str;
 		private Connection oms;

 		// 创建个构造函数初始化 list,和其他用到的参数
 		public MyThread(List<Map<String,Object>> list, CountDownLatch begin, CountDownLatch end,Map<String,Object> mapQueue,Connection con,String str,Connection oms) {
 			this.list = list;
 			this.begin = begin;
 			this.end = end;
 			this.mapQueue = mapQueue;
 			this.con = con;
 			this.str = str;
 			this.oms = oms;
 		}

 		@Override
 		public void run() {
 			System.out.println(str+"开始-------");
 			// 患者基本信息
            String _accountName = null;//患者账号
            String _id = null;//患者id
            String _babyName = null;//患者姓名
            String _queueId = null;//队列id
            String _code = null;//院code
            Map<String, String> params = new HashMap<String, String>();
            //随访1.0库
            Statement stm = null;
            Statement stmt2= null;
            Statement stmt3= null;
            Statement stmt4= null;
            Statement stmt8= null;
            int irow=0;
 			try {
 				stm = con.createStatement();
				stmt2 = con.createStatement();
	            stmt3 = con.createStatement();
	            stmt4 = con.createStatement();
	            stmt8 = oms.createStatement();
 				for (int i = 0; i < list.size(); i++) {
 					Map<String,Object> mapout = list.get(i);
	                params.clear();
	                irow++;
	                //通过 用户姓名，手机号码，和医院code查询乐惠用户信息t_archives
	                _accountName = (String) mapout.get("phone_no");
	                _babyName =(String) mapout.get("user_name");
	                _queueId = (String) mapout.get("queue_id");
	                _id = (String) mapout.get("id");
	                //通过队列id获取医院code
	                _code = (String) mapQueue.get(_queueId);
	                //乐惠用户查询sql
	                String sqlArchives = "select * from t_archives where _accountName = '"+_accountName+"' and _babyName='"+_babyName+"' and _code='"+_code+"'";
	                System.out.println("t_archives :"+sqlArchives);
	                ResultSet rs2 = stm.executeQuery(sqlArchives);
	                if(rs2==null) {
	                	continue;
	                }
	                String _babyId = "";
	                //获取第一条数据
	                if(rs2.first()) {
	                	//获取用户id
	                	_babyId = rs2.getString("_babyId");
	                	String sqlpackage = "select * from t_babyquestionnairepackage where _babyId='"+_babyId+"'";
	                	System.out.println("t_babyquestionnairepackage :"+sqlpackage);
	                	//获取宝宝问卷包，购买了哪些评估
	                	ResultSet rs3 = stm.executeQuery(sqlpackage);	
	                	if(rs3==null) {
	                		continue;
	                	}
	                	while(rs3.next()) {
	                		//获取包id
	                		String  _babyQuestionnairePackage_id = rs3.getString("_id");
	                		//查询用户问卷评估记录
	                		String sqlrecord = "select * from t_babyquestionrecord_20180419 where _babyQuestionnairePackage_id='"+_babyQuestionnairePackage_id+"' and _status='8' and deal_status = '2' ";
	                		System.out.println("t_babyquestionrecord_20180419 : "+sqlrecord);
	                		ResultSet rs4 = stmt2.executeQuery(sqlrecord);
	                		if(rs4==null) {
	                			continue;
	                		}
	                		/*if(rs3.getBoolean("_isGrowth")) {
	                		//生长发育评估	
	                			saveGrowth(rs4,stmt3,stmt4,"LeHuidept10001",_id,_queueId,con);
	                		}else*/ if("znfy".equals(rs3.getString("_questionCode"))) {
	                		//智能发育评估
	                			saveZnfy(rs4,stmt3,stmt4,"LeHuidept10001",_id,_queueId,con);
	                		}else if("yyhj".equals(rs3.getString("_questionCode"))) {
	                		//养育环境测量	
	                			saveYyhj(rs4,stmt3,stmt4,"LeHuidept10001",_id,_queueId,con);
	                		}
	                	}
	                }else {
	                	//没有查询到数据继续循环
	                	String updateSql = "update pt_user_info_lehui_02 set deal_status='3' where id='" + _id + "'";
	                	stmt8.executeUpdate(updateSql);
	                	oms.commit();
	                	continue;
	                }
	                //结束更新
	                String updateSql = "update pt_user_info_lehui_02 set deal_status='1' where id='" + _id + "'";
                	stmt8.executeUpdate(updateSql);
                	oms.commit();
 				}
 				// ....
 				// 执行完让线程直接进入等待
 				begin.await();
 			} catch (InterruptedException e) {
 				String updateSql = "update pt_user_info_lehui_02 set deal_status='0' where id='" + _id + "'";
   			 	try {
   			 		stmt8.executeUpdate(updateSql);
   			 		oms.commit();
				} catch (SQLException e1) {
					System.out.println();
				}
 				System.out.println(e);
 			} catch (NumberFormatException e) {
 				String updateSql = "update pt_user_info_lehui_02 set deal_status='0' where id='" + _id + "'";
   			 	try {
   			 		stmt8.executeUpdate(updateSql);
   			 		oms.commit();
				} catch (SQLException e1) {
					System.out.println();
				}
 				System.out.println(e);
			} catch (SQLException e) {
				String updateSql = "update pt_user_info_lehui_02 set deal_status='0' where id='" + _id + "'";
   			 	try {
   			 		stmt8.executeUpdate(updateSql);
   			 		oms.commit();
				} catch (SQLException e1) {
					System.out.println();
				}
				System.out.println(e);
			} catch (ParseException e) {
				String updateSql = "update pt_user_info_lehui_02 set deal_status='0' where id='" + _id + "'";
   			 	try {
   			 		stmt8.executeUpdate(updateSql);
   			 		oms.commit();
				} catch (SQLException e1) {
					System.out.println();
				}
				System.out.println(e);
			} finally {
 				// 这里要主要了，当一个线程执行完 了计数要减一不要这个线程会被一直挂起
 				// ，end.countDown()，这个方法就是直接把计数器减一的
				System.out.println("----------total: " + irow);
				System.out.println(str+"结束-------");
				try {
					stm.close();
					stmt2.close();
					stmt3.close();
					stmt4.close();
					stmt8.close();
				} catch (SQLException e) {
					System.out.println(e);
				}
 				end.countDown();
 			}
 		}

 	}
    
}



